package com.gw.vip.server.config;

import com.gw.vip.common.exception.ServiceException;
import com.gw.vip.server.bo.MailSenderInfo;
import com.gw.vip.server.constants.SysArgKey;
import com.gw.vip.server.service.dao_service.SysArgService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

/**
 * @author GW
 * @description
 * @since 2022-09-20
 */
@Configuration
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class JavaMailSenderConfig {

    private final SysArgService sysArgService;

    @Bean
    public JavaMailSender javaMailSender(){

        //获取邮件发送者信息
        MailSenderInfo mailSenderInfo = sysArgService.getObject(SysArgKey.MAIL_SENDER_INFO, MailSenderInfo.class);
        if (mailSenderInfo==null){
            log.error("邮件发送者不存在！");
            throw new ServiceException("邮件发送者不存在!");
        }

        JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
        try {
            javaMailSenderImpl.setHost("smtp.qq.com");
            javaMailSenderImpl.setPort(567);
            javaMailSenderImpl.setUsername(mailSenderInfo.getUserName());
            javaMailSenderImpl.setPassword(mailSenderInfo.getPassword());
            javaMailSenderImpl.getJavaMailProperties().put("mail.smtp.host", "smtp.qq.com");
            javaMailSenderImpl.getJavaMailProperties().put("mail.smtp.port", "465");
            javaMailSenderImpl.getJavaMailProperties().put("mail.debug", "true");
            javaMailSenderImpl.getJavaMailProperties().put("mail.smtp.auth", "true");
            javaMailSenderImpl.getJavaMailProperties().put("mail.smtp.starttls.enable", "true");
            javaMailSenderImpl.getJavaMailProperties().setProperty("mail.smtp.socketFactory.port", "465");
            javaMailSenderImpl.getJavaMailProperties().setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            javaMailSenderImpl.getJavaMailProperties().setProperty("mail.smtp.socketFactory.fallback", "false");
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return javaMailSenderImpl;
    }
}
